package com.jeff.android.lab.database.greendao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.jeff.android.lab.database.greendao.model.DaoMaster;
import com.jeff.android.lab.database.greendao.model.DaoSession;
import com.jeff.android.lab.database.greendao.model.Work;
import com.jeff.android.lab.database.greendao.model.WorkDao;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

public class GDDataManager {

    private final static String DB_NAME = "_green_dao_demo.db";
    private final static int DB_VERSION = 1;

    private static GDDataManager mInstance;
    private final Context mContext;
    private GDOpenHelper mOpenHelper;

    private GDDataManager(Context context) {
        mContext = context;
        mOpenHelper = new GDOpenHelper(context, DB_NAME, null);
    }

    public static GDDataManager instance(Context context) {
        if (mInstance == null) {
            synchronized (GDDataManager.class) {
                if (mInstance == null) {
                    mInstance = new GDDataManager(context);
                }
            }
        }
        return mInstance;
    }

    private SQLiteDatabase getReadableDatabase() {
        if (mOpenHelper == null)
            mOpenHelper = new GDOpenHelper(mContext, DB_NAME, null);
        return mOpenHelper.getReadableDatabase();
    }

    private SQLiteDatabase getWritableDatabase() {
        if (mOpenHelper == null)
            mOpenHelper = new GDOpenHelper(mContext, DB_NAME, null);
        return mOpenHelper.getWritableDatabase();
    }

    public void setDebugMode(boolean flag) {
        QueryBuilder.LOG_SQL = flag;
        QueryBuilder.LOG_VALUES = flag;
    }

    public void insert(Work work) {
        DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        WorkDao dao = daoSession.getWorkDao();
        dao.insert(work);
    }

    public Work query() {
        DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        WorkDao dao = daoSession.getWorkDao();
        QueryBuilder<Work> queryBuilder = dao.queryBuilder();
        List<Work> works = queryBuilder.list();

        return works.get(0);
    }

}
